package 用户登录界面实现.test01;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;

public class Test01 {
    static String realName = null;
    public static void main(String[] args) {
        Map<String,String> userLoginInfo = initUI();
        boolean loginSuccess = login(userLoginInfo);
        System.out.println(loginSuccess ? "恭喜您登录成功 欢迎回来: " + realName : "登录失败");
    }

    /**
     * 用户登录
     * @param userLoginInfo 用户登录信息
     * @return
     */
    private static boolean login(Map<String, String> userLoginInfo) {
        boolean loginSuccess = false;
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        Statement stmt = null;
        Connection conn = null;
        ResultSet rs = null;
        try {
            Class.forName(bundle.getString("driver"));
            String url = bundle.getString("url");
            String user = bundle.getString("user");
            String password = bundle.getString("password");
            conn = DriverManager.getConnection(url,user,password);
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from t_user where user = '"+ userLoginInfo.get("username") + "' and password = '" + userLoginInfo.get("password") + "'");
            if(rs.next()){
                realName = rs.getString(4);
                loginSuccess = true;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            if (conn == null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt == null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs == null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return loginSuccess;
    }

    /**
     * * 初始化用户界面
     *@return 用户输入的用户名和密码等信息
     */
    private static Map<String,String> initUI() {
        Scanner s = new Scanner(System.in);

        System.out.print("用户名: ");
        String username = s.nextLine();

        System.out.print("密码: ");
        String password = s.nextLine();

        Map<String,String> userLoginInfo = new HashMap<>();
        userLoginInfo.put("username",username);
        userLoginInfo.put("password",password);
        return userLoginInfo;
    }
}
